package com.rc.saas.tenant.controller.log;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.common.vo.log.ChargeProcessLogVo;
import com.rc.saas.tenant.common.vo.log.OrderTraceVo;
import com.rc.saas.tenant.model.member.MemberCard;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.log.ChargeProcessLogService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.log.ChargedProcessLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by sven on 2022-07-19
 */
@Controller
@RequestMapping("/tenantChargeLog")
public class TenantChargeLogController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(TenantChargeLogController.class);

    private String prefix = "/templates/log";

    @Autowired
    private ChargeProcessLogService chargeProcessLogService;

    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 跳转订单充电日志
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/orderProcessLog", method = RequestMethod.GET)
    public String chargeProcessLogIndex(Model model) {
        return prefix + "/tenantChargeLog";
    }

    /**
     * 跳转轨迹首页
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/orderTravel", method = RequestMethod.GET)
    public String orderTraceIndex(Model model) {
        return prefix + "/orderTracel";
    }

    /**
     * @param search
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/listChargeProcessLog", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listChargeProcessLog(ChargeProcessLogVo search) {
        logger.info("listChargeProcessLog,:{}", search.toString());

        int orderNum = StringUtils.isNotBlank(search.getOrderNum()) ? 1 : 0;
        int gunNo = StringUtils.isNotBlank(search.getGunNo()) ? 1 : 0;
        int nickName = StringUtils.isNotBlank(search.getNickName()) ? 1 : 0;
        int operatorName = StringUtils.isNotBlank(search.getOperatorName()) ? 1 : 0;

        //入参不能全部为空
        String isNull = "" + orderNum + operatorName + gunNo + nickName;
        if (!isNull.contains("1")) {
            logger.error("参数为空");
            return null;
        }

        PageImpl<ChargedProcessLog> pageInfo = chargeProcessLogService.findPageBySearch(search);
        logger.info("pageInfo.getTotal()).intValue():{}", pageInfo == null ? "null" : pageInfo.getTotalElements());

        //PageInfo转BootstrapPage
        if (pageInfo == null) {
            return null;
        }
        WebPageInfo bootstrapPage = new WebPageInfo(pageInfo.getContent(), Long.valueOf(pageInfo.getTotalElements()).intValue());
        return bootstrapPage;
    }

    /**
     * 导出充电实时信息列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(ChargeProcessLogVo search, HttpServletResponse response) {
        try {
            if(!Objects.isNull(search)){
                search.setLimit(1000);
            }
            int orderNum = StringUtils.isNotBlank(search.getOrderNum()) ? 1 : 0;
            int gunNo = StringUtils.isNotBlank(search.getGunNo()) ? 1 : 0;
            int nickName = StringUtils.isNotBlank(search.getNickName()) ? 1 : 0;
            int operatorName = StringUtils.isNotBlank(search.getOperatorName()) ? 1 : 0;

            //入参不能全部为空
            String isNull = "" + orderNum + operatorName + gunNo + nickName;
            if (!isNull.contains("1")) {
                logger.error("参数为空");
                return null;
            }

            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageImpl<ChargedProcessLog> pageInfo = chargeProcessLogService.findPageBySearch(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("充电实时信息列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ChargedProcessLog.class).sheet("充电实时信息列表").doWrite(pageInfo.getContent());
            return null;
        } catch (Exception e) {
            logger.error("导出充电实时信息列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * @param search operatorName; //加盟商名称
     *               stationNo; //桩编号
     *               pileNo; //充电枪编号
     *               beginTime; //开始时间  默认当天0点
     *               endTime; //结束时间
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/orderTrace", method = RequestMethod.GET)
    @ResponseBody
    public TResponse orderTrace(OrderTraceVo search) {
        logger.info("orderTrace,:{}", search.toString());
        if(StringUtils.isBlank(search.getPileNo())
                && StringUtils.isBlank(search.getOperatorName())
                && StringUtils.isBlank(search.getStationNo())
                && (null == search.getBeginTime())
                && (null == search.getEndTime()) ){
            return TResponse.FAIL("筛选条件不能全为空");
        }

        /*int pileNo = StringUtils.isNotBlank(search.getPileNo()) ? 1 : 0;
        int operatorName = StringUtils.isNotBlank(search.getOperatorName()) ? 1 : 0;
        int stationNo = StringUtils.isNotBlank(search.getStationNo()) ? 1 : 0;
        int beginTime = search.getBeginTime() == null ? 1 : 0;
        //入参不能全部为空
        String isNull = "" + pileNo + operatorName + stationNo + beginTime;
        if (!isNull.contains("1")) {
            return TResponse.FAIL("参数为空");
        }*/

        List<OrderTraceVo> orderTraceVos = orderInfoService.listOrderTrace(search);
        /*if (orderTraceVos == null) {
            return TResponse.FAIL("搜索加盟商或站点无数据，请检查搜索条件");
        }*/
        if (orderTraceVos == null) {
            orderTraceVos = new ArrayList<>();
            OrderTraceVo vo = new OrderTraceVo();
            vo.setTotalPower(BigDecimal.ZERO);
            vo.setOrderHour("23");
            orderTraceVos.add(vo);
            return TResponse.SUCCESS_DATA(orderTraceVos);
        }
        return TResponse.SUCCESS_DATA(orderTraceVos);
    }


    /**
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public String findById(String id, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime, Model model) {
        logger.info("findById,:{}", id);

        if (!StringUtils.isBlank(id)) {
            ChargedProcessLog log = chargeProcessLogService.findByOne(id, startTime);
            model.addAttribute("log", log);
        }
        return prefix + "/tenantChargeLogDetail";
    }
}
